﻿using System;
using System.Collections.Generic;
using System.Web.Http;
using System.Net.Http;
using Newtonsoft.Json;
using System.Net.Http.Headers;
using System.Xml;
using System.Data.SqlClient;
using System.Data;
using DataAccess;
using System.Web.Mvc;
using System.Web.UI;
using System.Web;

namespace WebApi.Controllers
{
    public class PopUpJoeController : ApiController
    {
        [System.Web.Http.AllowAnonymous]
        [System.Web.Http.HttpGet]
        [OutputCache(Duration=1, VaryByParam="none", Location=OutputCacheLocation.Any)]
        public HttpResponseMessage ProcessRequest(string parameter)
        {
            HttpContext.Current.Response.Cache.SetOmitVaryStar(true);

            var response = new HttpResponseMessage();

            if (!String.IsNullOrEmpty(parameter))
            {
                var xml = (XmlDocument)JsonConvert.DeserializeXmlNode(parameter);

                List<SqlParameter> parameters = new List<SqlParameter>();

                parameters.Add(new SqlParameter("xmlRequest", SqlDbType.Xml) { Value = xml.InnerXml });
                parameters.Add(new SqlParameter("biUpdUser", null));
                parameters.Add(new SqlParameter("xmlResponse", SqlDbType.Xml) { Direction = ParameterDirection.Output });

                var result = new DataSource().Execute("svc.uspWSProcess", parameters);
                var xmlResponse = result.Parameters["xmlResponse"].Value.ToString();

                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.InnerXml = xmlResponse;

                response.Content = new StringContent(JsonConvert.SerializeXmlNode(xmlDoc));
                response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            }

            return response;
        }
    }
}
